import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:zhibao_flutter/api/commom/common_entity.dart';
import 'package:zhibao_flutter/api/mine/mine_entity.dart';
import 'package:zhibao_flutter/api/user/user_entity.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/config/sp_key.dart';
import 'package:zhibao_flutter/util/data/get_install_info.dart';
import 'package:zhibao_flutter/util/func/sp_util.dart';
import 'package:zhibao_flutter/util/http/http.dart';
import 'package:zhibao_flutter/util/navibe/q1_android_util.dart';
import 'package:zhibao_flutter/zone.dart';
import 'package:get/get.dart';

class WeChatActions {
  static String msg() => 'msg';

  static String groupName() => 'groupName';

  static String voiceImg() => 'voiceImg';

  static String user() => 'user';
}

class Q1Data {
  static LoginRspEntity? loginRspEntity;
  static UserInfoEntity? userInfoEntity;

  // static RegisterBaseData? registerBaseData;
  // static SelfInfoRspEntity? selfInfoRspEntity;
  // static ShachaPicOptionRsp? shachaPicOptionRsp;
  static VersionRspEntity? versionRspEntity;

  static String loginPhone = "0";

  /// 临时token
  static String tempToken = "";

  /// 临时手机号/邮箱
  static String tempPhone = "";

  /// No necessary to agree the [User Agreement and Privacy policy] in
  /// the ios platform.
  ///
  /// Always true in new version.
  static RxBool isAgree = true.obs;

  // static RxBool isAgree = (!AppConfig.inProduction).obs;

  /// h5缓存更新机制：本地需增加一个管理h5版本的版本号{h5VersionCode}，默认值为-1。
  /// 安卓端调用app/getNewVersion接口时，若返回参数{h5VersionCode}大于本地的h5VersionCode
  /// 则会触发清除缓存重新加载h5。若若返回参数{h5VersionCode}小于等于本地的h5VersionCode则不作处理。
  /// （于1月18日新增说明）
  static int h5VersionCode = -1;

  /// Can't add start with in address/invite qrcode content.
  static var qrDataInvite = "$inviteCode";
  static var qrDataAddress = "$address";

  static String inviteCode = userInfoEntity?.inviteCode ?? "13100000000";

  static String address = userInfoEntity?.rechargeAddress ?? "0";

  static String get avatar {
    return getFullAvatar(userInfoEntity?.avatar ?? "");
  }

  static bool get hideMode {
    return false;
    if (kDebugMode) {
      return true;
    }
    return Q1Data.userInfoEntity?.deleted == 1;
  }

  static String getFullAvatar(String avatar) {
    final str = avatar ?? "";
    return strNoEmpty(str)
        ? str.startsWith(Environment.current)
            ? str
            : "${Environment.current}user/preview/$str"
        : "";
  }

  static String get phone {
    return userInfoEntity?.phone ?? userInfoEntity?.name ?? "";
  }

  static String get nickName {
    return userInfoEntity?.nickname ?? "";
  }

  static int get id {
    return userInfoEntity?.id ?? 0;
  }

  static int get grade {
    // if (!kReleaseMode) {
    //   return 4;
    // }
    return userInfoEntity?.grade ?? 0;
  }

  static bool get isLogin {
    return strNoEmpty(loginRspEntity?.token);
  }

  static Future init() async {
    try {
      await Q1DataRequest.initOfRequest();
      await initOfLoginResult();
      await initOfUserInfo();

      /// 获取手机序列号需要状态权限：FlutterDeviceIdentifier.serialCode
      await Q1DataRequest.initOfPublicParam();
      await Q1DataRequest.initOfLogParam();

      /// 获取经纬度需要定位权限[_determinePosition]
      // await Q1DataRequest.initOfOther();
    } catch (e) {
      LogUtil.d("get param info found error.::${e.toString()}");
    }
  }

  /// The method use of login out.
  static Future loginOut({bool verify = true}) async {
    SpUtil().setString(SpKey.loginResult, "");
    SpUtil().setString(SpKey.userInfo, "");

    /// Login out on memory.
    loginRspEntity = null;

    userInfoEntity = null;
    // selfInfoRspEntity = null;
    LogUtil.d("Login out success.");
  }

  static Future initOfLoginResult() async {
    String? loginResult = SpUtil().get(SpKey.loginResult);
    LogUtil.d("Fetch login result value $loginResult");
    try {
      if (strNoEmpty(loginResult)) {
        loginRspEntity = LoginRspEntity.fromJson(json.decode(loginResult!));
      }

      String? loginPhoneSpValue = SpUtil().get(SpKey.loginPhone);
      LogUtil.d("Fetch login phone result value $loginPhone");
      loginPhone = loginPhoneSpValue ?? "0";
    } catch (e) {
      LogUtil.d("initOfUserInfo() error is ${e.toString()}");
    }
  }

  static Future initOfUserInfo() async {
    String? userInfoStr = SpUtil().get(SpKey.userInfo);
    LogUtil.d("initOfUserInfo::userInfoStr::$userInfoStr");
    // try {
    if (strNoEmpty(userInfoStr)) {
      Q1Data.userInfoEntity =
          UserInfoEntity.fromJson(json.decode(userInfoStr!));
    }
    // } catch (e) {
    //   LogUtil.d("initOfUserInfo() error is ${e.toString()}");
    // }
  }

  static Future initUserIndex() async {
    // final selfInfoValue = await mineViewModel.userIndex(null);
    // if (selfInfoValue.data == null) {
    //   return;
    // }
    // Q1Data.selfInfoRspEntity = selfInfoValue.data;
    // needShowMindForChangeAvatar.value =
    //     Q1Data.selfInfoRspEntity?.iconChangeNeed == 1;
    // LogUtil.d(
    //     "needShowMindForChangeAvatar.value new value is ${needShowMindForChangeAvatar.value}");
  }
}

class Q1DataRequest {
  static String tag = "【Q1Data-baseInfo】 ";

  static String get deviceId {
    return deviceIdValue;
  }

  static String deviceIdValue = "";
  static String versionCode = "";
  static String deviceModel = "";

  static int version = 0;
  static String versionStrReal = "";
  static String versionStr = "1.0.0";

  static String buildNumber = "";
  static String packageName = "ZhiBao";

  // static String mac = "";

  /// channelID
  static String channelId = "SmartLoan";
  static String defImei = "000000000000000";
  static String imei = defImei;

  /// 暂时还没有地方用到
  /// Not used yet.
  static String packageSource = "GooglePlay";

  /// -----------------About settingsPublicParam--------↓
  static String installReferceClickTime = "";

  // static String installStartTime = "";

  // static String serial = "";
  static String deviceName = "";
  static String phoneBrand = "";
  static String sysVersion = "";
  static String countryCode = "";

  static String get language {
    return countryCode;
  }

  static String localeDisplayLanguage = "";

  static String localeIso3Country = "52";
  static String localeIso3Language = "es";
  static int apiLevel = 0;
  static String networkOperatorName = "";

  /// 是否使用vpn
  static bool isUsingProxyPort = false;

  /// -----------------About LogParam--------↓
  static String get phoneNumber {
    // return Q1Data.loginRspEntity?.mobile ?? Q1Data.loginPhone;
    return Q1Data.loginPhone;
  }

  /// no get [default value is "000"]
  static String merchantID = "000";

  static String get country {
    return countryCode;
  }

  static String get utmSource {
    return packageSource;
  }

  /// ------------------------------------------Other

  static double longitude = 0;
  static double latitude = 0;

  /// ------------------------------------------
  static int getReleaseDate = 0;

//  时区
//  TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)
  static String get timeZone {
    DateTime dateTime = DateTime.now();
    return dateTime.timeZoneName;
  }

  static Future initOfRequest() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionStrReal = packageInfo.version;
    versionStr = packageInfo.version;

    /// Debug mode can be implemented without device limitations.
    /// Avoid [设备绑定过多].
    /// Avoid [该设备绑定账号过多，无法注册新账号].
    final String extra =
        (kReleaseMode ? "" : "${3}"); //DateTime.now().millisecondsSinceEpoch

    // mac = await GetMac.macAddress;
    // LogUtil.d("${tag}mac value is $mac");

    try {
      Q1AndroidUtil().getImei().then((value) {
        if (strNoEmpty(value)) {
          imei = value;
        }
        LogUtil.d("${tag}imei value is $imei");
      });
    } on PlatformException {
      LogUtil.d('Failed to get Unique Identifier');
      LogUtil.d("${tag}imei value is $imei");
    }
    try {
      getReleaseDate = (await Q1AndroidUtil().getReleaseDate()) ?? 0;
      LogUtil.d("${tag}getReleaseDate value is $getReleaseDate");
    } catch (e) {
      LogUtil.d("${tag}getReleaseDate Error: ${e.toString()}");
    }
  }

  static Future initOfPublicParam() async {
    LogUtil.d("Q1DataRequest::initOfPublicParam");
    GetInstallInfo getInstallInfo = GetInstallInfo();

    try {
      int clickTimeInt =
          int.parse((await getInstallInfo.referrerClickTime()).toString());
      installReferceClickTime =
          MyDate.formatTimeStampToString(clickTimeInt, "yyyy-MM-dd kk:mm:ss");
      LogUtil.d(
          "${tag}installReferceClickTime value is $installReferceClickTime");
    } catch (e) {
      LogUtil.d("${tag}referrerClickTime Error is ${e.toString()}");
    }

    // try {
    //   int installTimeInt =
    //       int.parse((await getInstallInfo.appInstallTime()).toString());
    //   installStartTime =
    //       MyDate.formatTimeStampToString(installTimeInt, "yyyy-MM-dd kk:mm:ss");
    //   LogUtil.d("${tag}installStartTime value is $installStartTime");
    // } catch (e) {
    //   LogUtil.d("${tag}installStartTime Error is ${e.toString()}");
    // }

    // await FlutterDeviceIdentifier.requestPermission();
    // final bool hasPermission = await FlutterDeviceIdentifier.checkPermission();
    // LogUtil.d("FlutterDeviceIdentifier hasPermission $hasPermission");
    // if (hasPermission) {
    //   try {
    //     serial = await FlutterDeviceIdentifier.serialCode;
    //     LogUtil.d("${tag}serial value is $serial");
    //   } catch (e) {
    //     LogUtil.d(
    //         "FlutterDeviceIdentifier get serialCode fail, maybe not support version of current android. ");
    //   }
    // } else {
    //   LogUtil.d(
    //       "${tag}serial value is not permission of FlutterDeviceIdentifier");
    // }

    // try {
    //   /// Get info of [apiLevel] and [deviceName].
    //   apiLevel = await DeviceInformation.apiLevel;
    //   deviceName = await DeviceInformation.deviceName;
    //
    //   LogUtil.d("${tag}apiLevel value is $apiLevel");
    //   LogUtil.d("${tag}deviceName value is $deviceName");
    // } on PlatformException {
    //   LogUtil.d("[DeviceInformation] Failed to get platform version.");
    // }
  }

  /// 如果设备具有 VPN 连接，返回 true
  /// Has connect vpn will return true.
  static Future<bool> isVpnActive() async {
    bool isVpnActive;
    List<NetworkInterface> interfaces = await NetworkInterface.list(
        includeLoopback: false, type: InternetAddressType.any);
    interfaces.isNotEmpty
        ? isVpnActive = interfaces.any((interface) =>
            interface.name.contains("tun") ||
            interface.name.contains("ppp") ||
            interface.name.contains("pptp"))
        : isVpnActive = false;
    return isVpnActive;
  }

  static Future initOfLogParam() async {
    LogUtil.d("Q1DataRequest::initOfLogParam");
  }
}
